package com.daJiao.handler.wx;

import com.daJiao.builder.TextBuilder;
import com.daJiao.entity.SysSubscribeUser;
import com.daJiao.service.SysSubscribeUserService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * <p>Title:      SubscribeHandler. </p>
 * <p>Description 新用户关注事件 </p>
 * <p>Copyright: Copyright (c) 2016</p>
 * <p>Company:    医百科技有限公司 </p>
 *
 * @author <a href="yangwensheng@100doc.com.cn"/>杨文生</a>
 * @since 2021/2/27 17:17
 */
@Component
public class SubscribeHandler extends AbstractHandler {

    @Resource
    private SysSubscribeUserService sysSubscribeUserService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) throws WxErrorException {

        this.logger.info("新关注用户 OPENID={}", wxMessage.getFromUser());

        // 获取微信用户基本信息
        try {
            WxMpUser userWxInfo = weixinService.getUserService().userInfo(wxMessage.getFromUser(), null);
            if (userWxInfo != null) {
                SysSubscribeUser sysSubscribeUser = new SysSubscribeUser();
                BeanUtils.copyProperties(userWxInfo,sysSubscribeUser);
                sysSubscribeUser.setNickName(userWxInfo.getNickname());
                sysSubscribeUserService.saveSubscribeUser(sysSubscribeUser);
            }
        } catch (WxErrorException e) {
            if (e.getError().getErrorCode() == 48001) {
                this.logger.info("该公众号没有获取用户信息权限！");
            }
        }

        WxMpXmlOutMessage responseResult = null;
        try {
            responseResult = this.handleSpecial(wxMessage);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        if (responseResult != null) {
            return responseResult;
        }

        try {
            return new TextBuilder().build("您好，欢迎关注“因你同行”血友病患者关爱项目。" +
                    "本项目是由中国初级卫生保健基金会携手北京生命绿洲公益服务中心与神州细胞工程有限公司共同发起，" +
                    "为经医生诊断A型血友病患者提供服务", wxMessage, weixinService);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        return null;
    }

    /**
     * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
     */
    private WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage)
            throws Exception {
        //TODO
        return null;
    }

}
